package com.crack.nga2.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.view.menu.MenuPopupHelper;
import android.support.v7.widget.ListPopupWindow;
import android.support.v7.widget.PopupMenu;
import android.text.Html;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.crack.nga2.R;
import com.crack.nga2.activity.userCenter.PostStep1Activity;
import com.crack.nga2.custom.PullListView;
import com.crack.nga2.db.DBHelper;
import com.crack.nga2.entity.SubForum;
import com.crack.nga2.entity.Theme;
import com.crack.nga2.entity.data.ParsedThemeData;
import com.crack.nga2.utils.GlobalConst;
import com.crack.nga2.utils.TimeUtils;
import com.crack.nga2.utils.HttpParams;
import com.crack.nga2.volley.ThemeRequest;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * 论坛板块activity 用于呈现主题列表等
 * Created by Administrator on 2015/12/16.
 */
public class ForumActivity extends BaseActivity implements PopupMenu.OnMenuItemClickListener, AdapterView.OnItemClickListener, PullListView.OnRefreshListener {
    private SubForum forum;
    private PullListView listView;
    private int listViewIndex = 0;
    private List<Theme> themes = new ArrayList<>();
    private TitleAdapter adapter;
    private PopupMenu menu;
    protected int page;
    private MenuPopupHelper helper;
    /**
     * 是否正在刷新
     */
    private boolean isLoading = false;
    /**
     * 初始化是否完成
     */
    private boolean initCompleted = false;
    /**
     * 子版块列表
     */
    private ArrayList<SubForum> subForumList = new ArrayList<>();

    /**
     * 置顶帖信息
     */
    private int topicTid;

    /**
     * 请求
     */
    private RequestQueue mQueue;
    private DBHelper dbHelper;

    private Bundle bundle;

    private View fontLayout;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        mQueue = NgaApplication.getQueue();
        Intent intent = getIntent();
        forum = (SubForum) intent.getSerializableExtra("forum");
        adapter = new TitleAdapter();
        super.onCreate(savedInstanceState);
        initViews();
        page = 1;
        getData();
    }

    private void initViews() {
        if (listView != null) {
            listViewIndex = listView.getFirstVisiblePosition();
        }
        setContentView(R.layout.activity_forum);
        fontLayout = $(R.id.font_setting);
        dbHelper = new DBHelper(this);
        TextView tvTitle = (TextView) findViewById(R.id.action_title);
        tvTitle.setText(forum.getName());
        listView = (PullListView) findViewById(R.id.listView);
        listView.setOnItemClickListener(this);
        listView.setOnRefreshListener(this);
        listView.setAdapter(adapter);
        listView.setSelection(listViewIndex);
        setMenu();

    }

    private ImageView[] fontButtons = new ImageView[4];

    private PopupWindow fontPopupWindow;

    private void initFontSettingLayout() {
        if (fontPopupWindow == null) {
            fontLayout = View.inflate(this, R.layout.popupwindow_font_setting, null);
            fontPopupWindow = new PopupWindow(fontLayout, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            fontButtons[0] = $(fontLayout, R.id.font_small);
            fontButtons[1] = $(fontLayout, R.id.font_normal);
            fontButtons[2] = $(fontLayout, R.id.font_larget);
            fontButtons[3] = $(fontLayout, R.id.font_more_larget);
            for (int i = 0; i < 4; i++) {
                fontButtons[i].setOnClickListener(new FontClickListener());
            }
        }
        fontPopupWindow.setTouchable(true);
        fontPopupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });
        fontPopupWindow.setFocusable(true);
        fontPopupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.none));
    }

    private class FontClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.font_small:
                    CURRENT_THEME = THEME_SMALL_FONT;//0
                    break;
                case R.id.font_normal:
                    CURRENT_THEME = THEME_NORMAL_FONT;//1
                    break;
                case R.id.font_larget:
                    CURRENT_THEME = THEME_LARGET_FONT;//2
                    break;
                case R.id.font_more_larget:
                    CURRENT_THEME = THEME_MORE_LARGET_FONT;//3
                    break;
            }
            for (int i = 0; i < 4; i++) {
                if (i == CURRENT_THEME) {
                    fontButtons[i].setImageResource(R.drawable.diandian_on);
                } else {
                    fontButtons[i].setImageResource(R.drawable.none);
                }
            }
            setFontSize(CURRENT_THEME);
        }
    }


    private void setFontSize(int themeIndex) {
        isLoading = true;
        setCurrentTheme(themeIndex);
        initViews();
        isLoading = false;
    }

    /**
     * 发送请求
     */
    private void getData() {
        if (isLoading) {
            return;
        }
        isLoading = true;
        listView.onStartHeadRefresh();
        String url = getUrl();
        mQueue.add(new ThemeRequest(Request.Method.GET, url,
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        listView.onCompleteRefresh();
                        isLoading = false;
                    }
                },
                new Response.Listener<ParsedThemeData>() {
                    @Override
                    public void onResponse(ParsedThemeData response) {
                        if (page == 1) {
                            themes.clear();
                        }
                        themes.addAll(response.themeList);
                        topicTid = response.topicTid;
                        subForumList.clear();
                        subForumList.addAll(response.subForumList);
                        adapter.notifyDataSetChanged();
                        listView.onCompleteRefresh();
                        initCompleted = true;
                        isLoading = false;
                    }
                }));
    }

    @NonNull
    protected String getUrl() {
        HttpParams params = new HttpParams();
        params.put("fid", String.valueOf(forum.getFid()));
        params.put("page", page);
        params.put("lite", "js");
        return GlobalConst.BASE_URL + "thread.php?" + params.toString();
    }


    protected int getMenuResId() {
        return R.menu.menu_post_setting;
    }

    protected void setMenu() {
        View setting = findViewById(R.id.action_setting);
        menu = new PopupMenu(this, setting);
        menu.inflate(getMenuResId());
        MenuItem menuItem = menu.getMenu().findItem(R.id.menu_collect);
        if (menuItem != null) {
            boolean flag = dbHelper.isExists(forum.getFid(), DBHelper.DB_FORUM);
            menuItem.setTitle(flag ? "取消收藏" : "收藏");
            menuItem.setIcon(flag ? R.drawable.menu_favorited_night : R.drawable.menu_favorite);
        }
        menu.setGravity(Gravity.TOP);
        try {
            //强制显示图标
            Field field = menu.getClass().getDeclaredField("mPopup");
            field.setAccessible(true);
            helper = (MenuPopupHelper) field.get(menu);
            helper.setForceShowIcon(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        menu.setOnMenuItemClickListener(this);
    }

    private void movePopupMenu() {
        //移动菜单窗口
        try {
            Field fListPopup = helper.getClass().getDeclaredField("mPopup");
            fListPopup.setAccessible(true);
            ListPopupWindow window = (ListPopupWindow) fListPopup.get(helper);
            window.setVerticalOffset(-70);
            window.setHorizontalOffset(200);
            window.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void doClick(View view) {
        switch (view.getId()) {
            case R.id.action_return:
                finishForAnimation();
                break;
            case R.id.action_setting:
                if (!initCompleted) {
                    return;
                }
                //弹出菜单
                menu.show();
                movePopupMenu();
                break;
            case R.id.action_post:
                //跳转发帖页面
                Intent intent = new Intent(this, PostStep1Activity.class);
                intent.putExtra("fid", forum.getFid());
                intent.putExtra("action", "new");
                startActivity(intent);
                break;
            case R.id.iv_flush:
                if (!initCompleted || isLoading) {
                    return;
                }
                //刷新
                page = 1;
                getData();
                break;
        }
    }

    /**
     * 点击帖子
     */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Theme theme = (Theme) parent.getItemAtPosition(position);
        Intent intent = new Intent(this, FloorActivity.class);
        //传入主题id作为参数
        if (theme.getQuote_from() == 0) {
            intent.putExtra("theme", theme.getTid());
        } else {
            intent.putExtra("theme", theme.getQuote_from());
        }
        startActivity(intent);
    }

    /**
     * 点击菜单
     *
     * @param item 点击的item
     * @return 事件是否处理完成
     */
    @Override
    public boolean onMenuItemClick(MenuItem item) {
        Intent intent;
        switch (item.getItemId()) {
            case R.id.menu_collect:

                break;
            case R.id.menu_remind:
                intent = new Intent(this, RemindActivity.class);
                startActivity(intent);
                break;
            case R.id.menu_message:
                intent = new Intent(this, MessageActivity.class);
                startActivity(intent);
                break;
            case R.id.menu_sub:
                //子版块
                intent = new Intent(this, SubForumActivity.class);
                intent.putExtra("list", subForumList);
                intent.putExtra("forumName", forum.getName());
                intent.putExtra("ufid", forum.getFid());
                startActivityForResult(intent, 1);
                break;
            case R.id.menu_recommend:
                //精华区
                intent = new Intent(this, RecommendActivity.class);
                intent.putExtra("forum", forum);
                startActivity(intent);
                break;
            case R.id.menu_top:
                break;
            case R.id.menu_search:
                break;
            case R.id.menu_font_size:
                initFontSettingLayout();
                fontPopupWindow.showAtLocation((View) $(R.id.rootView), Gravity.BOTTOM, 0, 0);
                break;
            case R.id.menu_mode:
                break;
        }
        return false;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1 && resultCode == 1) {
            getData();
        }
    }

    /**
     * 下拉刷新
     */
    @Override
    public void pullDownToRefresh() {
        page = 1;
        getData();
    }

    /**
     * 上拉加载更多
     */
    @Override
    public void pullUpToRefresh() {
        page++;
        getData();
    }


    private class TitleAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return themes.size();
        }

        @Override
        public Object getItem(int position) {
            return themes.get(position);
        }

        @Override
        public long getItemId(int position) {
            return themes.get(position).getTid();
        }

        @Override
        public View getView(int position, View view, ViewGroup parent) {
            ViewHolder holder;
            if (view == null) {
                view = View.inflate(ForumActivity.this, R.layout.activity_forum_theme_item, null);
                holder = new ViewHolder();
                holder.postTitle = (TextView) view.findViewById(R.id.post_title);
                holder.postUserName = (TextView) view.findViewById(R.id.post_user_name);
                holder.lastReplyTime = (TextView) view.findViewById(R.id.post_reply_time);
                holder.replyCount = (TextView) view.findViewById(R.id.post_reply_count);
                view.setTag(holder);
            } else {
                holder = (ViewHolder) view.getTag();
            }
            Theme theme = themes.get(position);
            holder.postTitle.setText(Html.fromHtml(theme.getSubject()));
            holder.postUserName.setText(theme.getAuthor());
            holder.lastReplyTime.setText(TimeUtils.format(theme.getLastpost() * 1000));
            holder.replyCount.setText(String.valueOf(theme.getReplies()));
            return view;
        }
    }

    private class ViewHolder {
        TextView postTitle;
        TextView postUserName;
        TextView lastReplyTime;
        TextView replyCount;
    }
}
